﻿#region The MIT License
// The MIT License
// 
// Copyright (c) 2009 octalforty studios
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion

using System;
using System.Collections.Generic;
using System.Linq;

using Irony.Parsing;

namespace octalforty.Chinchillin.Console.Compiler
{
    public static class ParseTreeNodeExtensions
    {
        public static IEnumerable<ParseTreeNode> GetImmediateNodes(this ParseTreeNode node, string name)
        {
            if(node == null) throw new ArgumentNullException("node");

            if(node.Term.Name == name)
                yield return node;

            foreach(var n in node.ChildNodes.Where(n => n.Term.Name == name))
                yield return n;

            yield break;
        }

        public static IEnumerable<ParseTreeNode> GetNodes(this ParseTreeNode node, string name)
        {
            if(node == null) throw new ArgumentNullException("node");

            if(node.Term.Name == name)
                yield return node;

            foreach(var n in node.ChildNodes.SelectMany(childNode => GetNodes(childNode, name)))
                yield return n;

            yield break;
        }

        public static ParseTreeNode GetNode(this ParseTreeNode node, string name)
        {
            return GetNodes(node, name).FirstOrDefault();
        }

        public static ParseTreeNode GetNode(this ParseTreeNode node, string name, int skip)
        {
            return GetNodes(node, name).Skip(skip).FirstOrDefault();
        }

        public static IdentifierTerminal GetIdentifier(this ParseTreeNode node, string name)
        {
            return (IdentifierTerminal)GetNodes(node, "identifier").Where(n => n.Term is IdentifierTerminal && n.Token.Symbol.Text == name).FirstOrDefault().Term;
        }
    }
}
